package com.teufandsub.socialproximity.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;

/**
 * @author Bastien Mathias <bastienmathias@gmail.com>
 * @author Antoine Teuf <antoine.teuf@gmail.com>
 * @version 1.0
 * @since 2013-05-19
 * 
 * A class with some useful method which can be used in some different classes.
 */

public class Utils {

	private static final String EMAIL_PATTERN = 
			"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
			+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
	
	/**
	 * This method is used to encode the user's password with MD5
	 * 
	 * @param passwd The string non-encoded version of the password.
	 * @return String The string MD5 encoded version of the password.
	 */
	public static String toMD5(String passwd){
		String password = passwd;
		
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(password.getBytes());
			
			byte byteData[] = md.digest();
			
	        StringBuffer sb = new StringBuffer();	        
	        for (int i = 0; i < byteData.length; i++) {
	        	sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
	        }
	        
	        password = sb.toString();
		} catch (Exception e) {
			Log.e(Constants.APP_NAME, "MD5 conversion problem : " + e.toString());
		}
		
		
		return password;
	}
	
	/**
	 * Method used to know if the device is connected to a network.
	 * 
	 * @param context Context Context of the view where this method is called.
	 * @return boolean Return true if the device has connectivity otherwise return false.
	 */
    public static boolean hasConnectivity(Context context){
    	ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    	if(cm.getActiveNetworkInfo()==null){
    		return false;
    	}else{
    		return cm.getActiveNetworkInfo().isAvailable();
    	}  	
    }
	
    /**
     * This method is used to convert InputStream informations from the server to a JSONObject.
     * 
     * @param is InputStream informations return by the cloud application.
     * @return JSONObject JSONObject version of informations return by the applications.
     */
	public static JSONObject readResponse(InputStream is) {
	    String line = "";
	    StringBuilder total = new StringBuilder();

	    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

	    try {
		    while ((line = rd.readLine()) != null) { 
		        total.append(line).append("\n"); 
		    }
		} catch (Exception e) {
			Log.e(Constants.APP_NAME, "Unable to convert HTTPResponse : " + e.toString());
		}
	    JSONObject response = null;
	    try {
	    	response = new JSONObject(total.toString());  	
		} catch (Exception e) {
			Log.e(Constants.APP_NAME, "Unable to convert to JSONObject : " + e.toString());
		}
	    
	    return response;
	}
	
	/**
	 * Method to check is an email address is valid.
	 * 
	 * @param address String address mail to check
	 * @return boolean true if the address mail is valid, false otherwise.
	 */
	public static boolean validateEmail(String address){
		Pattern pattern = Pattern.compile(EMAIL_PATTERN);
		Matcher matcher = pattern.matcher(address);
			
		return matcher.matches();
	}
}
